package org.javaboy.security_mybatis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a.withObjectPostProcessor(new ObjectPostProcessor<AuthenticationManager>() {
                    @Override
                    public <O extends AuthenticationManager> O postProcess(O object) {
                        ProviderManager pm = (ProviderManager) object;
                        List<AuthenticationProvider> providers = pm.getProviders();
                        for (AuthenticationProvider provider : providers) {
                            if (provider instanceof DaoAuthenticationProvider dap) {
                                dap.setHideUserNotFoundExceptions(false);
                            }
                        }
                        return object;
                    }
                }).anyRequest().authenticated())
                .formLogin(f -> f
                        //由于 formLogin 这个方法主要是用来配置登录过滤器的，所以这里如果添加对象的后置处理器就是添加登录过滤器的后置处理器
                        .withObjectPostProcessor(new ObjectPostProcessor<UsernamePasswordAuthenticationFilter>() {
                            @Override
                            public <O extends UsernamePasswordAuthenticationFilter> O postProcess(O object) {
                                object.setUsernameParameter("name");
                                object.setPasswordParameter("passwd");
                                return object;
                            }
                        }).permitAll())
                .csrf(c -> c.disable());
        return http.build();
    }
}
